<script setup lang="ts">
import { AnswerService } from '@/service/Answer';
import * as echarts from 'echarts';
import Toast from 'primevue/toast';
import { useToast } from 'primevue/usetoast';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { CommonService } from '../common';

const currentPeriod = ref({
    Analysis: "",
    AnswerSN: "",
    AskName: "",
    AskSN: "",
    Chat: "",
    ChatList: [{ question: "", answer: "" }],
    Creattime: "",
    QuestionTemplate: "",
    Id: 0,
    isme: false
});

const displayRaw = ref(false);

const hornorList = ref();
const answerList = ref(null);
const currentUser = ref({
    Address: "",
    Birthday: "",
    Desc: "",
    Email: "",
    Face: "",
    Grade: "",
    Name: "",
    MotherName: "",
    MotherTel: "",
    FatherName: "",
    FatherTel: "",
    Sex: "",
    Status: "",
    Yicun: "",
    Liangcun: "",
    Class: "",
    Sn: "",
    Tel: ""
});
const route = useRoute();
const chartRef = ref<HTMLDivElement | null>(null);
let toast = null;
try {
    toast = useToast();
} catch (e) {
    console.warn('PrimeVue Toast 服务不可用:', e.message);
}
const radarValues = ref({
    texts: [{ text: "" }],
    values: [],
    Analysis: ""
}
);

// 错误处理函数
const handleError = (result) => {
    if (toast) {
        toast.add({ severity: 'error', summary: 'Error Message', detail: result.Title, life: 3000 });
    } else {
        // 降级处理：使用console输出
        console.error('Toast不可用:', result.Title);
    }
};

onMounted(() => {
    getUserInfo();
});

function getUserInfo() {
    if (route.params.sn) {
        AnswerService.queryUserAnswerList(route.params.sn, "1").then((result) => {
            if (result.Code != 1000) {
                handleError(result);
            } else {
                answerList.value = result.Data.answer;
                currentUser.value = result.Data.user;
                if (currentUser.value.Yicun.length > 3) {
                    currentUser.value.Face = currentUser.value.Yicun;
                } else if (currentUser.value.Liangcun.length > 3) {
                    currentUser.value.Face = currentUser.value.Liangcun;
                } else if (currentUser.value.Face.length > 3) {
                    currentUser.value.Face = currentUser.value.Face;
                } else {
                    currentUser.value.Face = "/upload/img.png";

                }
                hornorList.value = result.Data.hornor;
                if (answerList.value.length > 0) {
                    switchPeriod(answerList.value[0])
                }
                document.title = currentUser.value.Name + "综合评估"
            }
        }).catch((error) => {
            handleError({ Title: '查询用户出错', Code: -1 });
        });
    }
}

function open() {
    try {
        const chartDom = chartRef.value;
        if (chartDom) {
            const myChart = echarts.init(chartDom);
            const option: echarts.EChartsOption = {
                color: ['#ffF9D8', '#FFE434', '#56A3F1', '#FF917C'],
                title: {
                    show: false,
                },
                legend: {
                    textStyle: {
                        color: "#ffffff",
                        fontSize: 18
                    }
                },
                textStyle: {
                    fontSize: 18,
                },
                radar: [
                    {
                        indicator: radarValues.value.texts,
                        center: ['50%', '50%'],
                        radius: 180,
                        startAngle: 0,
                        splitNumber: 4,
                        shape: 'circle',
                        axisName: {
                            formatter: '{value}',
                            color: '#ffffff',
                        },
                        splitArea: {
                            areaStyle: {
                                color: ['#00EADF', '#26C3BE', '#64AFE9', '#428BD4'],
                                shadowColor: 'rgba(0, 0, 0, 0.2)',
                                shadowBlur: 10
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: 'rgba(211, 253, 250, 0.8)'
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                color: 'rgba(211, 253, 250, 0.8)'
                            }
                        }
                    }
                ],
                series: [
                    {
                        type: 'radar',
                        emphasis: {
                            lineStyle: {
                                width: 4
                            },
                        },
                        data: [
                            {
                                value: radarValues.value.values, // 使用响应式变量
                                name: '',
                                areaStyle: {
                                    color: 'rgba(0, 0, 255, 0.8)'
                                }
                            }
                        ]
                    }
                ]
            };
            if (option) {
                myChart.setOption(option);
            }
        } else {
            console.error('无法获取图表容器元素');
        }
    } catch (error) {
        console.error('初始化 ECharts 时出错:', error);
    }
}
function splitJsonData(jsonDataStr: string): [{ text: string }[], Number[]] {
    let jsonData: { [key: string]: { title: string, score: string } } = JSON.parse(jsonDataStr);
    let titles: { text: string, max: Number }[] = [];
    let scores: Number[] = [];
    for (let key in jsonData) {
        if (jsonData.hasOwnProperty(key)) {
            if (key == "Analysis") {
                radarValues.value.Analysis = jsonData[key].score;
            } else {

                // 将标题包装为 { text: string } 格式
                titles.push({ text: jsonData[key].title, max: 100 });
                scores.push(Number(jsonData[key].score));
            }
        }
    }
    return [titles, scores];
}

function switchPeriod(item) {
    if (!item) {
        console.error('无法获取switchPeriod 的item 元素');
        return
    }
    if (currentPeriod.value) {
        currentPeriod.value.isme = false;
    }
    item.isme = true;
    currentPeriod.value = item;
    // 判断 Chat 是否需要解析
    if (typeof currentPeriod.value.Chat === 'string') {
        try {
            currentPeriod.value.Chat = JSON.parse(currentPeriod.value.Chat);
        } catch (e) {
            console.error('解析 Chat 失败:', e);
        }
    }

    // 再次判断 Chat 是否需要解析
    if (typeof currentPeriod.value.Chat === 'string') {
        try {
            currentPeriod.value.ChatList = JSON.parse(currentPeriod.value.Chat);
        } catch (e) {
            console.error('解析 ChatList 失败:', e);
        }
    }

    // 修改后，
    const [texts, values] = splitJsonData(currentPeriod.value.Analysis);
    radarValues.value.texts = texts;
    radarValues.value.values = values;

    open();
}
</script>
<style>
fieldset {
    border: 2px #ffffff solid;
    border-radius: 5px;
    padding-bottom: 1rem;
}

legend {
    padding: 0.8rem;
}
</style>
<template>
    <div class="flex flex-wrap   min-h-screen justify-center pl-4 pr-4 "
        style="background-image: linear-gradient(to top, #09203f 0%, #537895 100%);">
        <Toast />
        <div class="text-center  md:w-full  lg:w-2/5  " style=" color: white;">
            <fieldset>
                <legend style="font-size: 2rem;"> {{
                    currentUser.Name
                }} </legend>
                <div class="grid grid-cols-2   " style="font-size: 1.5rem;">
                    <div class="flex justify-center">
                        <img :src="currentUser.Liangcun.length < 3 ? currentUser.Yicun : currentUser.Liangcun"
                            style="  max-height: 200px;  " alt="">
                    </div>
                    <div>
                        <div class="  m-1  text-left ">
                            性别:{{ currentUser.Sex }}
                        </div>
                        <div class=" m-1 text-left">
                            生日:{{ CommonService.formatDate(currentUser.Birthday) }}
                        </div>
                        <div class=" m-1 text-left">
                            电话:{{ currentUser.Tel }}
                        </div>
                        <div class=" m-1 text-left">
                            班级:{{ currentUser.Class }}
                        </div>
                        <div class=" m-1  text-left">
                            学号:{{ currentUser.Sn }}
                        </div>
                    </div>
                </div>
            </fieldset>
            <fieldset>
                <legend style="font-size: 1.5rem; text-align: left;">个人荣誉 </legend>
                <ul style="text-align: left;font-size: 1.5rem;">
                    <li v-for="(hornor, h) in hornorList" :key="h">
                        {{ CommonService.formatDate(hornor.GetDate) + " : " + hornor.Label }}</li>

                </ul>
            </fieldset>

        </div>
        <div class="flex flex-wrap justify-center md:w-full lg:w-3/5  ">
            <div ref="chartRef" id="main" class=" w-[800px]  h-[500px]"></div>
            <div class="flex md:w-full justify-center ">
                <Button :label="CommonService.formatFullDate(item.Creattime) + '  的' + item.QuestionTemplate"
                    :disabled="item.isme" @click="switchPeriod(item)" class="m-2"
                    style="height: 3rem;font-size: larger;" severity="help" v-for="(item, i) in answerList" :key="i">
                </Button>
            </div>
        </div>
        <div style="font-size: 1.5rem; color: white;">
            <fieldset>
                <legend>综合分析</legend>
                {{ radarValues.Analysis }}
                <button type="button" @click="displayRaw = !displayRaw" class=" bg-teal-300">原始访谈内容</button>
            </fieldset>
        </div>
        <Dialog v-model:visible="displayRaw" class="w-full" style="background-color:white" header="原始访谈内容"
            :modal="true">
            <div class="flex items-center gap-4">
                <ul style="font-size: 18px;">
                    <li v-for="(questionAnswer, index) in currentPeriod.ChatList" :key="index"
                        style="margin-bottom: 30px;">

                        <div style="color: black">
                            <span>第{{ index + 1 }}问:{{ questionAnswer.question }} </span>
                        </div>
                        <span class="mt-3 w-full bg-slate-600 " style="color: white;">{{ questionAnswer.answer }}</span>
                    </li>

                </ul>
            </div>
        </Dialog>
    </div>
</template>
